/*
 * Created on 24.04.2007
 */
package com.qjs.smterp.web.utils;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.qjs.smterp.utils.TextUtil;

/**
 * Contains different support utils for interation with FacesContext
 * 
 * 
 */
public abstract class FacesContextUtils {
	/**
	 * Adds message from exception to FacesContext message queue with 'ERROR'
	 * severity
	 * 
	 * @param e
	 *            info source exception. If null, then nothing happens
	 */
	public static void addErrorExceptionMessage(String id, Exception e) {
		if (e != null) {
			FacesMessage errorMsg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, getMessage(e), "");
			FacesContext.getCurrentInstance().addMessage(id, errorMsg);
		}
	}

	public static void addErrorExceptionMessage(Exception e) {
		addErrorExceptionMessage(null, e);
	}

	public static void addErrorExceptionMessage(String error) {
		if (error != null) {
			FacesMessage errorMsg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, error, "");
			FacesContext.getCurrentInstance().addMessage(null, errorMsg);
		}
	}

	public static void addInfoMessage(String info) {
		if (info != null) {
			FacesMessage infoMsg = new FacesMessage(FacesMessage.SEVERITY_INFO,
					info, "");
			FacesContext.getCurrentInstance().addMessage(null, infoMsg);
		}
	}

	public static String getMessage(Throwable th) {
		if (th != null) {
			th = getCause(th);
			return (th.getMessage() == null) ? th.getClass().getName() : th
					.getMessage();
		}
		return null;
	}

	public static Throwable getCause(Throwable th) {
		Throwable thCause = th;
		while (th != null) {

			th = thCause.getCause();
		}
		return thCause;
	}

	public static MethodExpression getActionExpression(String action) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		return ctx
				.getApplication()
				.getExpressionFactory()
				.createMethodExpression(ctx.getELContext(), action, null,
						new Class<?>[0]);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getValueExpression(String value, Class<T> clazz) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		ELContext etx = ctx.getELContext();
		ValueExpression valueExpression = ctx.getApplication()
				.getExpressionFactory()
				.createValueExpression(etx, value, clazz);
		return (T) valueExpression.getValue(etx);
	}

	public static URL getResource(String path) throws MalformedURLException {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getResource(path);
	}

	public static InputStream getResourceAsStream(String path)
			throws MalformedURLException {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getResourceAsStream(path);
	}

	public static void addLocalizedInfoMessage(String bundleName,
			String msgKey, String defaultMessage) {
		addInfoMessage(getStringFromBundle(bundleName, msgKey, defaultMessage));
	}

	public static void addLocalizedErrorExceptionMessage(String bundleName,
			String msgKey, String defaultMessage) {
		addErrorExceptionMessage(getStringFromBundle(bundleName, msgKey,
				defaultMessage));
	}

	public static void addLocalizedErrorExceptionMessage(String bundleName,
			String msgKey, String defaultMessage, Exception exc) {
		StringBuilder sb = TextUtil.addIfNotNull(new StringBuilder(),
				getStringFromBundle(bundleName, msgKey, defaultMessage));
		if (exc != null) {
			sb.append(" ").append(getCause(exc).getLocalizedMessage());
		}
		addErrorExceptionMessage(sb.toString());
	}

	public static String getStringFromBundle(String bundleName, String msgKey,
			String defaultMessage) {
		try {
			ResourceBundle bundle = getResourceBundle(bundleName);
			return bundle.getString(msgKey);
		} catch (Exception ex) {
			return defaultMessage;
		}
	}

	public static ResourceBundle getResourceBundle(String name) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		Locale locale = ctx.getViewRoot().getLocale();
		return ResourceBundle.getBundle(name, locale);
	}

	public static Object getSessionObject(String objectName) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) ctx.getExternalContext()
				.getSession(false);
		if (session != null) {
			Object value = session.getAttribute(objectName);
			return value;
		}
		return null;
	}
}
